//--------------------------------------------------------------------
//
//    Copyright (C) Streamlet. All rights reserved.
//
//    File Name:   DllMain.cpp
//    Author:      Streamlet
//    Create Time: 2015-01-05
//    Description: 
//
//    Version history:
//
//
//--------------------------------------------------------------------



#include <Windows.h>
#include <xl/Meta/xlScopeExit.h>
#include <xl/Win32/COM/xlComModule.h>
#include "Global.h"
#include "Register.h"


STDAPI DllCanUnloadNow()
{
    return xl::g_pComModule->DllCanUnloadNow();
}

STDAPI DllGetClassObject(_In_ REFCLSID rclsid, _In_ REFIID riid, _Outptr_ LPVOID *ppv)
{
    return xl::g_pComModule->DllGetClassObject(rclsid, riid, ppv);
}

STDAPI DllUnregisterServer()
{
    bool bSucceeded = true;

    if (!Register::UnregisterCategories())
    {
        bSucceeded = false;
    }

    if (!Register::UnregisterProfiles())
    {
        bSucceeded = false;
    }

    HRESULT hr = xl::g_pComModule->DllUnregisterServer();

    if (!bSucceeded && SUCCEEDED(hr))
    {
        hr = E_FAIL;
    }

    return hr;
}

STDAPI DllRegisterServer()
{
    xl::ScopeGuard sgUnregister = xl::MakeGuard(DllUnregisterServer);
    HRESULT hr = xl::g_pComModule->DllRegisterServer();

    if (FAILED(hr))
    {
        return hr;
    }

    if (!Register::RegisterProfiles())
    {
        return E_FAIL;
    }

    if (!Register::RegisterCategories())
    {
        return E_FAIL;
    }

    sgUnregister.Dismiss();
    return S_OK;
}

STDAPI DllInstall(BOOL bInstall, _In_opt_ LPCTSTR lpszCmdLine)
{
    return E_NOTIMPL;
}

BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
{
    switch (ul_reason_for_call)
    {
    case DLL_PROCESS_ATTACH:
        Global::hDLL = hModule;
        xl::g_pComModule = new xl::ComModule(hModule, _T("xlUSKeyborad TypeLib 1.0"));
        break;
    case DLL_THREAD_ATTACH:
        break;
    case DLL_THREAD_DETACH:
        break;
    case DLL_PROCESS_DETACH:
        delete xl::g_pComModule;
        Global::hDLL = NULL;
        break;
    default:
        break;
    }

    return TRUE;
}

